package frame.security.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import frame.common.BaseService;
import frame.common.Config;
import frame.common.ConstantEntity;
import frame.common.Message;
import frame.exception.FrameException;
import frame.security.entity.User;
import frame.utils.RandomValidateCode;

/**
 * 这个类就像门的作用一样，起到区分内部外部的作用。
 * 进入系统，离开系统都需要经过这个门。
 * 这个类还提供获取验证码，用户注册的功能，类似于进门登记，获取认证的意思。
 * @author MR.CUIPENG
 *
 */
@Controller
@RequestMapping("/gate")
public class Gate extends BaseService{
	
	private static final long serialVersionUID = -8892670157406050316L;
	
	@Autowired
	private Cache ehCache;
	//向response中返回一个验证码图片
	@RequestMapping(value = "/validateCode", method = RequestMethod.GET)
	public void getValidateCode(HttpServletRequest request, HttpServletResponse response){
		response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        randomValidateCode.getRandcode(request, response);//输出图片方法
	}
	
	/**
	 * 检测用户登录用的id是否被注册。
	 * @param user_id
	 * @return
	 */
	@RequestMapping(value = "/checkUserID", method = RequestMethod.POST)
	@ResponseBody
	public Message checkUserId(String user_id){
		int n=dao.queryObject("checkUserID", Integer.class, user_id);
		if(n==0){
			return Message.OK;//操作成功
		}else{
			return new Message("FSI0001");//该邮箱已被使用！
		}
	}
	
	//用户注册 需要输入用户信息和一个验证码
	@RequestMapping(value = "/regsit", method = RequestMethod.POST)
	@ResponseBody
	public Message insertUser(@Valid User user,String validateCode,BindingResult result){
		Subject currentUser = SecurityUtils.getSubject();
		String validate=(String)currentUser.getSession().getAttribute(ConstantEntity.VALIDATE_CODE);
		if(validate.equalsIgnoreCase(validateCode)){
			//TODO 可能需要在后台校验邮箱是否被使用
			user.setUser_type(ConstantEntity.USER_TYPE_C);
//			dao.updateObject("insertUser", user,"user_id","user_id","user_type","password");
			dao.updateObject("insertUser", user,"user_id","user_name","password");
			return new Message("FSE0005");//通过验证 TODO erro
		}else{
			return Message.ADD_OK;//新增成功
		}
	}
	
	@RequestMapping(value = "/userlogin", method = RequestMethod.POST)
	@ResponseBody
	public String login(@Valid User user,BindingResult result){
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUser_id(),user.getPassword());
		token.setRememberMe(true);
		try {
			currentUser.login(token);
			user=(User)currentUser.getSession().getAttribute("current_user");
			Element e=new Element(user.getUser_id(), user);
			ehCache.put(e);//当前用户加入到缓冲
		} catch (AuthenticationException e) {
			return "没有通过认证";
		}
		currentUser.getSession().setAttribute("current_user", user);//将用户对象加入当前会话
		String index=(String)Config.getContextProperty("indexPage");
		System.out.println("the index page is :"+index);
		return index;//the page after common user login
	}
	
	@RequestMapping(value = "/mgrlogin")
	@ResponseBody
	public String login4m(@Valid User user,BindingResult result){
		Subject currentUser = SecurityUtils.getSubject();
		
		System.out.println("sessionID is "+currentUser.getSession().getId());
		
		if(currentUser.isAuthenticated()){
			return "frame/mgr/mgr.jsp";
		}else{
			if(currentUser.isRemembered()){
				return "frame/mgr/mgr.jsp";
			}else{
				UsernamePasswordToken token = new UsernamePasswordToken(user.getUser_id(),user.getPassword());
				token.setRememberMe(true);
				try {
					currentUser.login(token);
					user=(User)currentUser.getSession().getAttribute("current_user");
					Element e=new Element(user.getUser_id(), user);
					ehCache.put(e);//当前用户加入到缓冲
					if(!"M".equals(user.getUser_type())){
						throw new FrameException("该用户不是管理员");
					}
				} catch (AuthenticationException e) {
					return "frame/errorPage";
				}
				currentUser.getSession().setAttribute("current_user", user);//将用户对象加入当前会话
				return "frame/mgr/mgr.jsp";//the page  after manager login
			}
			
		}
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(){
		Subject currentUser = SecurityUtils.getSubject();
        if (SecurityUtils.getSubject().getSession() != null){
            currentUser.logout();
        }
		return "index";//the page  after manager login
	}

}
